package zmee.pur.src.formplugin;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: xw
 * @Date: 2022/12/06/9:46
 * @Description: 资质后审审核后把通用报价单金额信息反写到报价分析对应字段
 */
public class AptitudeAuditAuditRetrographyPlugin extends AbstractBillPlugIn {

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs args) {
        super.afterDoOperation(args);
        String operateKey = args.getOperateKey();
        if ("audit".equals(operateKey)) {
            if (args.getOperationResult().isSuccess()) {
                long projectId = (long) this.getModel().getValue("id");
                String billNo = (String) this.getModel().getValue("billno");
                QFilter filter = new QFilter("parentid", "=", projectId);
                DynamicObject object = BusinessDataServiceHelper.loadSingleFromCache("src_purlist_stand", "id", filter.toArray());
                if (null == object) {
                    return;
                }
                //资信评审通用报价单
                DynamicObject purList = BusinessDataServiceHelper.loadSingleFromCache(object.getPkValue(), "src_purlist_stand");
                DynamicObjectCollection entryEntity = purList.getDynamicObjectCollection("entryentity");
                for (DynamicObject dynamicObject : entryEntity) {
                    String sysresult = dynamicObject.getString("sysresult");
                    if ("7".equals(sysresult)) {
                        continue;
                    }
                    long supplierId = dynamicObject.getDynamicObject("supplier").getLong("id");
                    long materialId = dynamicObject.getDynamicObject("material").getLong("id");
                    long entryRcvOrgId = dynamicObject.getDynamicObject("entryrcvorg").getLong("id");
                    int pruListSeq = dynamicObject.getDynamicObject("purlist").getInt("purlistseq");
                    QFilter filter1 = new QFilter("project.billno", "=", billNo).and("entrystatus", "=", "C").and("supplier.id", "=",
                            supplierId).and("material.id", "=", materialId).and("entryrcvorg", "=", entryRcvOrgId).and("purlist" +
                            ".purlistseq", "=", pruListSeq);
                    //报价分析
                    DynamicObject obj = BusinessDataServiceHelper.loadSingle("src_analysetool", "id,price,amount,taxitem,taxrate,tax," +
                            "taxprice,taxamount,locprice,loctaxprice,locamount,loctaxamount", filter1.toArray());
                    obj.set("price", dynamicObject.getBigDecimal("price"));
                    obj.set("locprice", dynamicObject.getBigDecimal("price"));
                    obj.set("amount", dynamicObject.getBigDecimal("amount"));
                    obj.set("locamount", dynamicObject.getBigDecimal("amount"));
                    obj.set("taxitem", dynamicObject.get("taxitem"));
                    obj.set("taxrate", dynamicObject.getBigDecimal("taxrate"));
                    obj.set("tax", dynamicObject.getBigDecimal("tax"));
                    obj.set("taxprice", dynamicObject.getBigDecimal("taxprice"));
                    obj.set("loctaxprice", dynamicObject.getBigDecimal("taxprice"));
                    obj.set("taxamount", dynamicObject.getBigDecimal("taxamount"));
                    obj.set("loctaxamount", dynamicObject.getBigDecimal("taxamount"));
                    SaveServiceHelper.save(new DynamicObject[]{obj});
                }

                DynamicObject srcType = (DynamicObject) this.getModel().getValue("srctype");
                String number = srcType.getDynamicObject("sourcetype").getString("number");
                if ("C010406".equals(number)) {

                    //自动议价方案为竞争性谈判且按物料的重新按未税金额排名
                    DynamicObject projectRule = BusinessDataServiceHelper.loadSingle("src_project_rule", "id,extfilter", filter.toArray());
                    String extfilterNumber = projectRule.getDynamicObject("extfilter").getString("number");
                    QFilter filter1 = new QFilter("project.billno", "=", billNo).and("entrystatus", "=", "C");
                    DynamicObject[] analysetools = BusinessDataServiceHelper.load("src_analysetool",
                            "id,rank,amount,material,supplier," + "sysresult,result,orderratio,cfmqty,qty", filter1.toArray());
                    if ("negotiate004".equals(extfilterNumber)) {
                        Map<Long, List<DynamicObject>> listMap =
                                Arrays.stream(analysetools).collect(Collectors.groupingBy(a -> a.getLong("material.id")));
                        for (Map.Entry<Long, List<DynamicObject>> entry : listMap.entrySet()) {
                            List<DynamicObject> dynamicObjectList = entry.getValue();
                            dynamicObjectList =
                                    dynamicObjectList.stream().sorted(Comparator.comparing(d -> d.getBigDecimal("amount"))).collect(Collectors.toList());
                            for (int i = 1; i <= dynamicObjectList.size(); i++) {
                                DynamicObject obj = dynamicObjectList.get(i - 1);
                                obj.set("rank", i);
                                if (i == 1) {
                                    obj.set("sysresult", "1");
                                    obj.set("result", "1");
                                    obj.set("orderratio", new BigDecimal("100"));
                                    obj.set("cfmqty", obj.get("qty"));
                                } else {
                                    obj.set("sysresult", "3");
                                    obj.set("result", "3");
                                }
                            }
                        }
                        SaveServiceHelper.save(analysetools);
                    }
                }/*else if ("negotiate002".equals(extfilterNumber)) {
                    Map<Long, Double> rankMap = new HashMap<Long, Double>(8);
                    Map<Long, List<DynamicObject>> listMap = Arrays.stream(analysetools).collect(Collectors.groupingBy(a -> a.getLong(
                            "supplier.id")));
                    for (Map.Entry<Long, List<DynamicObject>> entry : listMap.entrySet()) {
                        Long key = entry.getKey();
                        List<DynamicObject> dynamicObjectList = entry.getValue();
                        double amountSum = dynamicObjectList.stream().mapToDouble(d -> Double.parseDouble(String.valueOf(d.getBigDecimal(
                                "amount")))).sum();
                        rankMap.put(key, amountSum);
                    }
                    List<Map.Entry<Long, Double>> collect =
                            rankMap.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toList());
                    for (int i = 1; i <= collect.size(); i++) {
                        Long key = collect.get(i - 1).getKey();
                        for (DynamicObject analysetool : analysetools) {
                            long supplierId = analysetool.getLong("supplier.id");
                            if (key == supplierId) {
                                analysetool.set("rank", i);
                            }
                        }
                    }
                    SaveServiceHelper.save(analysetools);
                }*/
            }
        } else if ("save".equals(operateKey)) {
            this.getView().invokeOperation("refresh");
        }
    }
}
